using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
using UnityEngine.EventSystems;

namespace JEngine.Framework
{
    public class RayHelper
    {
        


        private Dictionary<string, List<IRayHandle>> layerMap = new Dictionary<string, List<IRayHandle>>();
        private Dictionary<string, List<IRayHandle>> tagMap = new Dictionary<string, List<IRayHandle>>();
        private Dictionary<string, List<IRayHandle>> nameMap = new Dictionary<string, List<IRayHandle>>();

        public RayHelper()
        {
            var list = Engine.GetInterfaces<IRayHandle>();
            foreach (var type in list)
            {
                RayAttribute att = type.GetCustomAttribute<RayAttribute>();
                if (att != null && !type.IsAbstract)
                {
                    string namekey = att.name;
                    IRayHandle api = Activator.CreateInstance(type) as IRayHandle;
                    switch (att.rayType)
                    {
                        case RayType.gameObject_name:
                            if (nameMap.ContainsKey(namekey))
                            {
                                nameMap[namekey].Add(api);
                            }
                            else
                            {
                                nameMap.Add(namekey, new List<IRayHandle> {api});
                            }

                            break;
                        case RayType.gameObject_layer:
                            if (layerMap.ContainsKey(namekey))
                            {
                                layerMap[namekey].Add(api);
                            }
                            else
                            {
                                layerMap.Add(namekey, new List<IRayHandle> {api});
                            }

                            break;
                        case RayType.gameObject_tag:
                            if (tagMap.ContainsKey(namekey))
                            {
                                tagMap[namekey].Add(api);
                            }
                            else
                            {
                                tagMap.Add(namekey, new List<IRayHandle> {api});
                            }

                            break;
                    }
                }
            }

           
        }

        public void Update()
        {
            // 同时支持PC和移动端输入检测
            bool inputDetected = false;
            Vector2 inputPosition = Vector2.zero;

            // PC端输入
            if (Input.GetMouseButtonDown(0))
            {
                inputDetected = true;
                inputPosition = Input.mousePosition;
            }
            // 移动端输入
            else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
            {
                inputDetected = true;
                inputPosition = Input.GetTouch(0).position;
            }

            if (!inputDetected) return;

            // 检查是否点击在UI上（同时处理PC和移动端）
            if (IsPointerOverGameObject(inputPosition))
            {
                return;
            }

            // 执行射线检测
            Ray ray = Camera.main.ScreenPointToRay(inputPosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, float.MaxValue))
            {
                // 原有处理逻辑
                string namekey=  hit.collider.gameObject.name.Replace("(Clone)", "");
                string tagkey=  hit.collider.gameObject.tag;
                string layerkey = LayerMask.LayerToName(hit.collider.gameObject.layer);
                if (nameMap.ContainsKey(namekey))
                {
                    foreach (var VARIABLE in nameMap[namekey])
                    {
                        VARIABLE.Handle(hit.collider.gameObject);
                    }
                }
                if (tagMap.ContainsKey(tagkey))
                {
                    foreach (var VARIABLE in tagMap[tagkey])
                    {
                        VARIABLE.Handle(hit.collider.gameObject);
                    }
                }
                if (layerMap.ContainsKey(layerkey))
                {
                    foreach (var VARIABLE in layerMap[layerkey])
                    {
                        VARIABLE.Handle(hit.collider.gameObject);
                    }
                }
            }
        }

        // 改进的UI检测方法（同时支持PC和移动端）
        private  bool IsPointerOverGameObject(Vector2 mousePosition)
        {
            //创建一个点击事件
            PointerEventData eventData = new PointerEventData(EventSystem.current);
            eventData.position = mousePosition;
            List<RaycastResult> raycastResults = new List<RaycastResult>();
            //向点击位置发射一条射线，检测是否点击UI
            EventSystem.current.RaycastAll(eventData, raycastResults);
            if (raycastResults.Count > 0)
            {
                bool isui = raycastResults[0].gameObject.layer == LayerMask.NameToLayer("UI");
                if (raycastResults[0].gameObject.name.StartsWith("UIMain"))
                    return false;
                return isui;
            }
            else
            {
                return (false);
            }
        }
    }
}